var express = require('express');
var router = express.Router();
var Promise = require('promise');
var accountService = require('./service/AccountService');
var fansService = require('./service/EnFansService');
var wechatRest = require('../utils/en_wechatRest');
var interceptor = require('../utils/interceptor');
var common = require('../utils/commonUtils');
var logger = require('log4js').getLogger('wechat.js');
var conf = require('../../config');

// 获取企业号的用户信息
router.get('/auth/:authType', function (req, res, next) {
    var authType = req.params.authType;
    var code = req.query.code;
    var state = req.query.state;
    var account = req.session.account;
    logger.debug(req.originalUrl);
    Promise.resolve(account).then(function (account) {
        if (!account) {
            return accountService.getById(9).then(function (r) {
                account = r;
                req.session.account = r;
                return Promise.resolve(r);
            });
        } else {
            return Promise.resolve(account);
        }
    }).then(function (account) {
        if (code) {
            // code换取openid
            return accountService.verifyEn_AccessToken(account).then(function (result) {
                if (req.session.authScope == conf.wechat.baseScope) {
                    return fansService.getUserIdByAccessToken(result.accessToken, code);
                } else {
                    return fansService.getUserIdByAccessToken(result.accessToken, code);
                }
            })
        } else {
            return Promise.resolve(null);
        }
    }).done(function (fans) {

        if (fans) {
            req.session.fans = fans;
            res.redirect(state);
        } else {
            // 未拿到粉丝信息，重新请求授权
            if (authType == 'base') {
                //只拿userid
                req.session.authScope = conf.en_wechat.baseScope;
            } else {
                //拿userid以及详细信息
                req.session.authScope = conf.en_wechat.userScope;
            }
            var redirectUri = '/en_wechat/auth/' + authType;
            res.redirect(wechatRest.getRedirectUrls(req.session.account, redirectUri, req.session.authScope, state));
        }
    }, function (err) {
        logger.error('auth2:', req.session);
        logger.error('auth3:', err);
        res.status(500).end();
    });

});

router.get('/jssdkSign', function (req, res, next) {
    //url = "http://m.muzhibuluo.com/h5/2cat/startup.html?code=123";
    var url = req.query.url;
    if (common.isUrl(url)) {
        var urlSplit = url.split('/');
        if (urlSplit.length > 1 && urlSplit[2].indexOf("m.muzhibuluo.com") >= 0) {
            next();
            return;
        }
    }
    res.json({success: false});
    return;
}, interceptor.verifyJsTicket, function (req, res) {
    var url = req.query.url;
    var account = req.session.account || {};
    if (url && account.jsTicket) {
        var ret = wechatRest.sign(req.session.account.jsTicket, url);
        var data = {
            appId: req.session.account.appId, // 微信签名参数
            timestamp: ret.timestamp,
            nonceStr: ret.nonceStr,
            signature: ret.signature
        };
        res.json({success: true, data: data});
    } else {
        res.json({success: false});
    }

});


module.exports = router;